
//TCP server
var net=require('net');
var server=net.createServer();
clientList=[];

server.on('connection',function(client)
{
    var alldata="";
    console.log('连接成功');
    var id=client.remoteAddress+":"+client.remotePort;
    console.log('客户端：'+id);
    client.name=id;

    client.on('data',function(data)
    {
       alldata+=data;
        console.log('recv:',data);
        broadcast(data,client);
    })
    client.on('end',function()
    {
        console.log('客户端关闭');
        clientList.splice(clientList.indexOf(client),1);
        console.log("!!delete");
    });
    client.on('error',function(err)
    {
        console.error(err);
    });
    client.write('Hello world');
    clientList.push(client);

    //connection.pipe(connection);
});
function broadcast(msg,client)
{
    var cleanup=[];
    for(var i=0;i<clientList.length;i++)
    {
        if(client==clientList[i])
            continue;
        if(clentList[i].writeable)
        {
            clientList[i].write(client.name+"says:"+msg);
        }
        else
        {
            cleanup.push(clientList[i]);
            clientList[i].destroy();
        }

    }
    for(i==0;i<cleanup.length;i++)
    {
        clientList.splice(clientList.indexOf(cleanup[i]),1);
        console.log("delete");
    }

}
server.listen(8080,function()
{
    console.log('server is listening');
});